//
//  CTCommentTable.m
//  cactus
//
//  Created by wd on 11-12-1.
//  Copyright 2011年 ifeng. All rights reserved.
//

#import "CTCommentTable.h"

#import "CommentCommonCell.h"
#import "CommentManyReplyCell.h"
#import "CalculatHeightForReplayCell.h"
#import "CommentFailedCell.h"
#import <CoreText/CoreText.h>
#import "CTCommentViewController.h"
#import "NSString+URLEncoding.h"
#import "CLGloble.h"

#import "CommentHeaderCell.h"
#import "CLComentDataModel.h"

#define standar_time +(8*60*60)
#define mix 15 //时间和出处
#define max 15 //内容

#define ctColor [UIColor colorWithRed:80.0/255.0 green:80.0/255.0 blue:80.0/255.0 alpha:1.0]
#define ctTimeColor [UIColor colorWithRed:179.0/255.0 green:179.0/255.0 blue:179.0/255.0 alpha:1.0]
#define ctContentColor [UIColor blackColor]

@interface CTCommentTable()
- (commnetCellType)judgeCommentCellType:(NSDictionary *)data;
- (BOOL)indexPath:(NSIndexPath *)sourceIndexPath isExistInArray:(NSArray *)array;
- (void)addReplayAtTableView:(UITableView *)tableView  atIndexPath:(NSIndexPath *)indexPath;
@property (nonatomic,assign) int pageindex;
@end

@implementation CTCommentTable
@synthesize wwwUrl,uuid,content,ctDelegate,body,replayCommentId,documentId;
@synthesize showHiddenFloorIndexPaths;
@synthesize hottestComments,myComments;

- (void)dealloc
{
   
    
}

- (void)supportClickedWihtIndexPath:(NSDictionary *)dic{
    if([self.ctDelegate respondsToSelector:@selector(supportClickedWihtIndexPath:)]){
        [self.ctDelegate performSelector:@selector(supportClickedWihtIndexPath:)
                              withObject:dic];
    }
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.uuid =[NSString stringWithFormat:@"%@",@"snow"];
        self.table=[[UITableView alloc] initWithFrame:frame];
        [self addSubview:self.table];
        self.table.delegate = self;
        self.table.dataSource = self;
        bLoadingMore = NO;
        self.pageindex=1;
      
      //  [self performSelector:@selector(createBottom)];
    
        showHiddenFloorIndexPaths = [[NSMutableArray alloc] init];
    }
    return self;
}

//-(void)initMyComments:(BOOL)isReloadTable{
//    self.myComments = [[NSMutableArray alloc] init];
//    [[MyCommentService shareInstance] queryWithId:self.documentId WithCompleteBlock:(MyCommentServiceQueryCompleteBlock)^(NSArray *results){
//        for (int i = 0; i<[results count]; i++) {
//            MyCommentEntity *myCommentEntity = (MyCommentEntity *)[results sgrGetForIndex:i];
//            NSDictionary *datadic = [myCommentEntity.comment_data objectFromJSONString];
//            if (datadic && [datadic isKindOfClass:[NSDictionary class]]) {
//                NSDate *myCommentDate = [NSDate dateFromString:[datadic sgrGetStringForKey:@"comment_date"]];
//                NSDictionary *lastCommentDic = [(NSArray *)[self.content expansionValueForKey:@"newest"] sgrGetDictionaryForIndex:0];
//                NSDate *lastCommentDate = [NSDate dateFromString:[NSString stringWithFormat:@"%@:00",[lastCommentDic sgrGetStringForKey:@"comment_date"]]];
//                if(!lastCommentDate ||([[lastCommentDate earlierDate:myCommentDate] isEqualToDate:lastCommentDate]))
//                    [self.myComments sgrAddObject:datadic];
//            }
//        }
//        if (isReloadTable) {
//            [self tableReloadData];
//        }
//    }];
//}
-(void)createBottom{
    if (_refreshBottomView == nil) {
        EGORefreshTableBottomView *bottom = [[EGORefreshTableBottomView alloc]
                                             initWithFrame:CGRectMake(0, GlobleHeight, GlobleWidth,
                                                                      GlobleHeight)];
        //bottom.backgroundColor = ICurrentTheme.commentStyle.comment_bgColor;
        bottom.backgroundColor=RGB(0xf7, 0xf7, 0xf7);
        bottom.delegate = self;
        [self.table addSubview:bottom];
        _refreshBottomView = bottom;
    }
}
-(void)hidenBottom{
    
    [_refreshBottomView setHidden:YES];
}
-(void)tableReloadData{
    [self.table reloadData];
    [self performSelector:@selector(resetButtomFrame)];
}
#pragma mark -
#pragma mark Judge Cell Type
//判断数据适用于哪一种cell类型

- (commnetCellType)judgeCommentCellType:(NSDictionary *)data
{
    if(!data || ![data isKindOfClass:[NSDictionary class]])
        return commonCommentType;
    if([self performSelector:@selector(hasCommentReplay:) withObject:data])
        return commentReplayType;
    return commonCommentType;
}

- (BOOL)hasCommentReplay:(NSDictionary *)data
{
    NSArray *parentCommentArray = [data sgrGetArrayForKey:@"parent"];
    if(!parentCommentArray
       || ![parentCommentArray isKindOfClass:[NSArray class]]
       || [parentCommentArray count] <= 0)
        return NO;
    return YES;
}

#pragma mark - 代理

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (2==section) {
        return 0;
    }
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, 320, 50);
    headerView.backgroundColor =RGB(0xf7, 0xf7, 0xf7);
    
    UILabel *sectionLab = [UILabel new];
    sectionLab.backgroundColor = [UIColor clearColor];
    sectionLab.font = [UIFont boldSystemFontOfSize:16];
    sectionLab.textColor = RGB(0xf5, 0x43, 0x43);
    sectionLab.frame = CGRectMake(15, 19, 200, 16);
    
    NSString *text = nil;
    if(section == 0)
    {
        text = @"| 热门评论";
    }
    else if (1==section)
    {
        text = @"| 最新评论";
    }
    sectionLab.text = text;
    [headerView addSubview:sectionLab];
    
    UIView *line = [UIView new];
    line.frame = CGRectMake(53, CGRectGetHeight(headerView.frame)-0.5, 258, 0.5);
    line.backgroundColor = RGB(0xd7, 0xd7, 0xd7);
    [headerView addSubview:line];
    
    return headerView;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    if (self.myComments && [self.myComments count]) {
//        return 3;
//    }
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

  
    float height = 0.f;
    
    if(indexPath.section == 0)
    {
        if(!hottestComments || [hottestComments count] == 0)
            height = 45; //表示错误cell的高度
        else{
            NSDictionary *hottestData = [hottestComments sgrGetDictionaryForIndex:indexPath.row];
            NSInteger type = [self judgeCommentCellType:hottestData];
            if(type == commentReplayType){
                BOOL needShowHiddenedComments = NO;
                if([self indexPath:indexPath isExistInArray:self.showHiddenFloorIndexPaths])
                    needShowHiddenedComments = YES;
                height = [CalculatHeightForReplayCell calculationHeightWithData:hottestData
                                                              isShowAllComments:needShowHiddenedComments];
            }
            else{
                height = [CalculatHeightForReplayCell calculationCommonCommentHeightWithData:hottestData];
            }
        }
    }
    else if ((1==indexPath.section) && self.myComments && [self.myComments count] ) {

        NSDictionary *commentData = [self.myComments sgrGetDictionaryForIndex:indexPath.row];
        NSInteger type = [self judgeCommentCellType:commentData];
        if(type == commentReplayType){
            BOOL needShowHiddenedComments = NO;
            if([self indexPath:indexPath isExistInArray:self.showHiddenFloorIndexPaths])
                needShowHiddenedComments = YES;
            height = [CalculatHeightForReplayCell calculationHeightWithData:commentData
                                                          isShowAllComments:needShowHiddenedComments];
        }
        else
        {
            height = [CalculatHeightForReplayCell calculationCommonCommentHeightWithData:commentData];
        }
    }
    else
    {
        NSArray *newComments = (NSArray *)[self.content sgrGetArrayForKey:@"newest"];
        if(!newComments || [newComments count] == 0)
            height = 45;
        else{
            NSDictionary *commentData = [newComments sgrGetDictionaryForIndex:indexPath.row];
            NSInteger type = [self judgeCommentCellType:commentData];
            if(type == commentReplayType){
                BOOL needShowHiddenedComments = NO;
                if([self indexPath:indexPath isExistInArray:self.showHiddenFloorIndexPaths])
                    needShowHiddenedComments = YES;
                height = [CalculatHeightForReplayCell calculationHeightWithData:commentData
                                                              isShowAllComments:needShowHiddenedComments];
            }
            else
            {
                height = [CalculatHeightForReplayCell calculationCommonCommentHeightWithData:commentData];
            }
        }
    }
    return height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.myComments && [self.myComments count] && (1==section)) {
        return [self.myComments count];
    }
    
    NSInteger count = 0;
    if(section == 0)
    {
        if(hottestComments && [hottestComments count]>0)
            count = [hottestComments count];
        else
            count = 1;
    }
    else
    {
        NSArray *newestComments = [content sgrGetArrayForKey:@"newest"];
        if(newestComments && [newestComments count] > 0)
            count = [newestComments count];
        else if(section ==2){
            count = 0;
        }
        else
            count = 1;
    }
    return count;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    BOOL hasSupported = NO;
    if(self.ctDelegate && [self.ctDelegate respondsToSelector:@selector(isSupportedComment:)])
        hasSupported = [(CTCommentViewController *)self.ctDelegate isSupportedComment:indexPath];
    if (self.myComments && [self.myComments count] && (1==indexPath.section)) {
        static NSString *commonCellIdentifier = @"mycommenCell";
        static NSString *replayCommonCellIndentifier = @"replayMyCommonCell";
        NSDictionary *commentData = (NSDictionary *)[self.myComments sgrGetForIndex:indexPath.row];
   
        NSInteger type = [self judgeCommentCellType:commentData];
        if(type == commonCommentType)
        {
            CommentCommonCell *cell = (CommentCommonCell *)[tableView dequeueReusableCellWithIdentifier:commonCellIdentifier];
            if(cell == nil){
                
                cell = [[CommentCommonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:commonCellIdentifier];
            }
            cell.dataDic = commentData;
            cell.comeFrom = @"comment";
            cell.delegate = self;
            cell.indexPath = indexPath;
            cell.isSupported = hasSupported;
            cell.isSupportClick = NO;
            [cell setUpSubViews];
            return cell;
        }
        else
        {
            CommentManyReplyCell *cell = (CommentManyReplyCell *)[tableView dequeueReusableCellWithIdentifier:replayCommonCellIndentifier];
            if(cell == nil){
                cell = [[CommentManyReplyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:replayCommonCellIndentifier];
            }
            if([self indexPath:indexPath isExistInArray:self.showHiddenFloorIndexPaths]){
           
                cell.isShowAllComments = YES;
            }else{
                cell.isShowAllComments = NO;
            }
            cell.delegate = self;
            cell.isSupported = hasSupported;
            cell.isSupportClick = NO;
            cell.dataDic = commentData;
            cell.indexPath = indexPath;
            [cell setUpSubViews];
            return cell;
        }
    }
    
    if(indexPath.section == 0)
    {
        if(hottestComments && [hottestComments count] > 0)
        {
            static NSString *commonCellIdentifier = @"commenCell";
            static NSString *replayCommonCellIndentifier = @"replayCommonCell";
            NSDictionary *commentData = [[self.content sgrGetArrayForKey:@"hottest"] sgrGetDictionaryForIndex:indexPath.row];
            NSInteger type = [self judgeCommentCellType:commentData];
            if(type == commonCommentType)
            {
                CommentCommonCell *cell = (CommentCommonCell *)[tableView dequeueReusableCellWithIdentifier:commonCellIdentifier];
                if(cell == nil){
                    
                    cell = [[CommentCommonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:commonCellIdentifier];
                }
                cell.dataDic = commentData;
                cell.delegate = self;
                cell.comeFrom = @"comment";
                cell.indexPath = indexPath;
                cell.isSupported = hasSupported;
                cell.isSupportClick = YES;
                [cell setUpSubViews];
                cell.autoresizesSubviews=NO;
                cell.autoresizingMask=UIViewAutoresizingNone;
                return cell;
            }
            else
            {
                CommentManyReplyCell *cell = (CommentManyReplyCell *)[tableView dequeueReusableCellWithIdentifier:replayCommonCellIndentifier];
                if(cell == nil){
                    cell = [[CommentManyReplyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:replayCommonCellIndentifier];
                }
                if([self indexPath:indexPath isExistInArray:self.showHiddenFloorIndexPaths])
                    cell.isShowAllComments = YES;
                else
                    cell.isShowAllComments = NO;
                cell.delegate = self;
                cell.isSupported = hasSupported;
                cell.isSupportClick = YES;
                cell.dataDic = commentData;
                cell.indexPath = indexPath;
                [cell setUpSubViews];
             
                return cell;
            }
        }
        else   //错误的cell
        {
            static NSString *commentFailedCellIdentifier = @"failedCell";
            CommentFailedCell *cell = (CommentFailedCell *)[tableView dequeueReusableCellWithIdentifier:commentFailedCellIdentifier];
            
            if(cell == nil)
            {
                cell = [[CommentFailedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:commentFailedCellIdentifier];
            }
            
            NSNumber *commentCount=[self.commentsDic sgrGetNumberForKey:@"count"];
            NSArray *comments = [self.content sgrGetArrayForKey:@"hottest"];
            NSString *failedShowStr = nil;
            if([commentCount integerValue] == 0 || (comments && [comments count] ==0))
                failedShowStr = @"暂无评论";
            else
                failedShowStr = @"加载失败";
            cell.failedShowStr = failedShowStr;
            [cell setUpSubviews];
          
            return cell;
        }
    }
    else
    {
        if([content sgrObjectForKey:@"newest"] && [(NSArray *)[content sgrGetArrayForKey:@"newest"] count]>0)
        {
            static NSString *commonCellIdentifier = @"commenCell";
            static NSString *replayCommonCellIndentifier = @"replayCommonCell";
            NSDictionary *commentData = [[self.content sgrGetArrayForKey:@"newest"] sgrGetDictionaryForIndex:indexPath.row];
            NSInteger type = [self judgeCommentCellType:commentData];
            if(type == commonCommentType)
            {
                CommentCommonCell *cell = (CommentCommonCell *)[tableView dequeueReusableCellWithIdentifier:commonCellIdentifier];
                if(cell == nil){
                    
                    cell = [[CommentCommonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:commonCellIdentifier];
                    
                }
                
                cell.dataDic = commentData;
                cell.comeFrom = @"comment";
                cell.delegate = self;
                cell.isSupported = hasSupported;
                cell.isSupportClick = YES;
                cell.indexPath = indexPath;
                [cell setUpSubViews];
             

                return cell;
            }
            else
            {
                CommentManyReplyCell *cell = (CommentManyReplyCell *)[tableView dequeueReusableCellWithIdentifier:replayCommonCellIndentifier];
                if(cell == nil){
                    cell = [[CommentManyReplyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:replayCommonCellIndentifier];
                    
                }
                if([self indexPath:indexPath isExistInArray:self.showHiddenFloorIndexPaths])
                    cell.isShowAllComments = YES;
                else
                    cell.isShowAllComments = NO;
                cell.delegate = self;
                cell.dataDic = commentData;
                cell.isSupported = hasSupported;
                cell.isSupportClick = YES;
                cell.indexPath = indexPath;
                [cell setUpSubViews];
              
                return cell;
            }
        }
        else    //错误的cell
        {
            static NSString *commentFailedCellIdentifier = @"failedCell";
            CommentFailedCell *cell = (CommentFailedCell *)[tableView dequeueReusableCellWithIdentifier:commentFailedCellIdentifier];
            if(cell == nil)
            {
                cell = [[CommentFailedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:commentFailedCellIdentifier];
            }
            NSNumber *commentCount=[self.commentsDic sgrGetNumberForKey:@"count"];
            NSDictionary *comments = [self.content sgrGetDictionaryForKey:@"newest"];
            NSString *failedShowStr = nil;
            if([commentCount integerValue] ==0 || (comments && [comments count] == 0))
                failedShowStr = @"暂无评论";
            else
                failedShowStr = @"加载失败";
            cell.failedShowStr = failedShowStr;
            [cell setUpSubviews];
         
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPat{
    [tableView deselectRowAtIndexPath:indexPat animated:NO];
}
- (void)addReplayAtIndexPath:(NSIndexPath *)indexPath
          withLocateInWindow:(CGPoint)locateInWindow
            withLocateInCell:(CGPoint)locateInCell
              withSizeOfCell:(CGSize)sizeOfCell
               withSourceDic:(NSDictionary *)dic
         atParentsArrayIndex:(NSInteger)parentsArrayIndex
                   withLevel:(NSNumber *)level
                        withView:(UIView *)view
{
    if(self.ctDelegate && [self.ctDelegate respondsToSelector:@selector(addassistantViewwithLocateInWindow:withLocateInCell:withSizeOfCell:withIndexPath:withSourceDataDic:atParentsArrayIndex:withLevel:withView:)]){
        [(CTCommentViewController *)self.ctDelegate
         addassistantViewwithLocateInWindow:locateInWindow
         withLocateInCell:locateInCell
         withSizeOfCell:sizeOfCell
         withIndexPath:indexPath
         withSourceDataDic:dic
         atParentsArrayIndex:parentsArrayIndex
         withLevel:level
         withView:view];
    }
}

- (void)requestmoreData{
    __weak typeof(self) me=self;
    [[CLComentDataModel sharedInstance] loadTopicWithTitle:((CTCommentViewController *)self.ctDelegate).docTitle
                                                     topicId:((CTCommentViewController *)self.ctDelegate).commentTopicId
                                                 pageNum:self.pageindex+1
                                                   block:^(BOOL success, NSDictionary *dic) {
                                                       if(success){
                                                           me.pageindex++;
                                                           NSArray *arr=[[dic sgrGetDictionaryForKey:@"comments"]
                                                                                                  sgrGetArrayForKey:@"newest"];
                                                           
                                                           if(!arr || ![arr isKindOfClass:[NSArray class]] || [arr count] == 0){
                                                                               [self setCommentFail];
                                                                               return;
                                                                           }
                                                           NSArray *orarr=[me.content sgrGetArrayForKey:@"newest"];
                                                           NSArray *hot=[me.content sgrGetArrayForKey:@"hottest"];
                                                           NSMutableArray *newarr=[NSMutableArray array];
                                                           if(orarr)
                                                                    [newarr addObjectsFromArray:orarr];
                                                            if(arr && [arr isKindOfClass:[NSArray class]])
                                                                    [newarr addObjectsFromArray:arr];
                                                           
                                                           NSNumber *count=[dic sgrGetNumberForKey:@"count"];
                                                            NSNumber *join_count=[dic sgrGetNumberForKey:@"join_count"];
                                                           NSMutableDictionary *dic=[NSMutableDictionary dictionary];
                                                           [dic sgrSetObject:count forKey:@"count"];
                                                           [dic sgrSetObject:join_count forKey:@"join_count"];
                                                           NSMutableDictionary *comments=[NSMutableDictionary dictionary];
                                                                       [comments sgrSetObject:hot forKey:@"hottest"];
                                                                       [comments sgrSetObject:newarr forKey:@"newest"];
                                                                       [dic sgrSetObject:comments forKey:@"comments"];
                                                                       [me setCommentData:dic];

                                                           
                                                       }else{
                                                           [me setCommentFail];
                                                       }
                                                   }];
    
//    if(_isStrNULL(self.wwwUrl)) return;
//    NSString *url=[[Globle shareInstance] getAbsolutlyUrlById:@"getComment"];
//    url=[NSString stringWithFormat:url,@"20",[NSString stringWithFormat:@"%d",self.pageindex+1],[self.wwwUrl URLEncodedString]];
//    IfengData_Request *request=[[IfengData_Request alloc] init];
//    request.url=url;
//    request.isAppendStandardParam=NO;
//    request.dataType=IfengData_Json;
//    request.priority=IfengData_RequestIgnoreCache;
//    request.cacheType=IfengData_CacheType_webCache;
//    CTCommentTable __weak *me=self;
//    [request onResponse:^(IfengData_Response *response){
//        if(response && [response responseCode]==0 &&
//           response.responseObject && [response.responseObject respondsToSelector:@selector(objectForKey:)]){
//            me.pageindex++;
//            NSArray *arr=[[response.responseObject sgrGetDictionaryForKey:@"comments"]
//                          sgrGetArrayForKey:@"newest"];
//            if(!arr || ![arr isKindOfClass:[NSArray class]] || [arr count] == 0){
//                [self setCommentFail];
//                return;
//            }
//            NSArray *orarr=[me.content sgrGetArrayForKey:@"newest"];
//            NSArray *hot=[me.content sgrGetArrayForKey:@"hottest"];
//            
//            NSNumber *count=[response.responseObject sgrGetNumberForKey:@"count"];
//            NSNumber *join_count=[response.responseObject sgrGetNumberForKey:@"join_count"];
//            NSMutableArray *newarr=[NSMutableArray arrayWithCapacity:[arr count]+[orarr count]];
//            if(orarr)
//                [newarr addObjectsFromArray:orarr];
//            if(arr && [arr isKindOfClass:[NSArray class]])
//                [newarr addObjectsFromArray:arr];
//            NSMutableDictionary *dic=[NSMutableDictionary dictionary];
//            [dic sgrSetObject:count forKey:@"count"];
//            [dic sgrSetObject:join_count forKey:@"join_count"];
//            NSMutableDictionary *comments=[NSMutableDictionary dictionary];
//            [comments sgrSetObject:hot forKey:@"hottest"];
//            [comments sgrSetObject:newarr forKey:@"newest"];
//            [dic sgrSetObject:comments forKey:@"comments"];
//            [me setCommentData:dic];
//            
//            
//        }else{
//            [me setCommentFail];
//        }
//    }];
//    [request send:self];
    
}

#pragma mark -
#pragma mark -辅助
- (void)egoRefreshTableBottomDidTriggerRefresh:(EGORefreshTableBottomView*)view{
    [self performSelector:@selector(reloadTableViewDataSourceMore)];
}
-(void)reloadTableViewDataSourceMore{
    bLoadingMore = YES;
    [self requestmoreData];
    _isGettingMore = YES;
}
- (BOOL)egoRefreshTableBottomDataSourceIsLoading:(EGORefreshTableBottomView*)view{
	return _isGettingMore;
}
- (void)resetButtomFrame{
    _isGettingMore = NO;
    [_refreshBottomView egoChangeBottomItemFrame:self.table];
    [_refreshBottomView egoRefreshScrollViewDataSourceDidFinishedLoading:self.table];
}
-(void)doneLoadingTableView{
	[_refreshBottomView egoRefreshScrollViewDataSourceDidFinishedLoading:self.table];
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self setWhenTableDragCellBgUserInteractionEnabled:NO];
    
    if(ctDelegate && [ctDelegate respondsToSelector:@selector(tableViewDidScroll:)])
        [ctDelegate performSelector:@selector(tableViewDidScroll:) withObject:scrollView];
    
    [_refreshBottomView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self setWhenTableDragCellBgUserInteractionEnabled:NO];
    
    if(ctDelegate && [ctDelegate respondsToSelector:@selector(tableViewWillBeginDragging:)])
        [ctDelegate performSelector:@selector(tableViewWillBeginDragging:) withObject:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self setWhenTableDragCellBgUserInteractionEnabled:YES];
    
    if (!decelerate) {
        if(ctDelegate && [ctDelegate respondsToSelector:@selector(tableViewDidEndDraggingWithNotDecelerate:)])
            [ctDelegate performSelector:@selector(tableViewDidEndDraggingWithNotDecelerate:) withObject:scrollView];
    }
    [_refreshBottomView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self setWhenTableDragCellBgUserInteractionEnabled:YES];
    
    if(ctDelegate && [ctDelegate respondsToSelector:@selector(tableViewDidEndDecelerating:)])
        [ctDelegate performSelector:@selector(tableViewDidEndDecelerating:) withObject:scrollView];
}
#pragma mark -
#pragma mark - table移动时，控制cell点击背景效果关闭／打开
-(void)setWhenTableDragCellBgUserInteractionEnabled:(BOOL)flag{
    NSArray *visibleCells = [self.table visibleCells];
    for (UITableViewCell *cell in visibleCells) {
        if ([cell isKindOfClass:[CommentCommonCell class]]) {
            UIView *bgLabel = [cell.contentView viewWithTag:10];
            if (bgLabel && [bgLabel isKindOfClass:[IfengLabel class]]) {
                bgLabel.userInteractionEnabled = flag;
            }
        }
        else if([cell isKindOfClass:[CommentManyReplyCell class]]){
            UIView *bgLabel = [cell.contentView viewWithTag:10];
            if (bgLabel && [bgLabel isKindOfClass:[IfengLabel class]]) {
                bgLabel.userInteractionEnabled = flag;
            }
        }
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        return;
    }
    else if(buttonIndex == 1)
    {
        [self reloadTableViewDataSourceMore];
    }
}

#pragma mark - Request Data Methods

- (BOOL)hasCommentData
{
    if(!self.commentsDic)
        return NO;
    return YES;
}

- (void)setCommentData:(NSDictionary *)dataDic{
   // self.hidden=NO;
    isReceviedSuccessed = YES;
    if(self.ctDelegate && [self.ctDelegate respondsToSelector:@selector(finishedLaodData)])
        [self.ctDelegate performSelector:@selector(finishedLaodData)];
    self.commentsDic=dataDic;
    self.content=[dataDic sgrGetDictionaryForKey:@"comments"];
    if (self.content && ![self.content isKindOfClass:[NSNull class]]){
        self.hottestComments=[self.content sgrGetArrayForKey:@"hottest"];
        [self.table reloadData];
        [self performSelector:@selector(resetButtomFrame)];
    }else{
        [self.table reloadData];
        [self hidenBottom];
    }
}

- (void)setCommentFail{
    self.hidden = NO;
    isReceviedSuccessed = NO;
    
    if(self.ctDelegate && [self.ctDelegate respondsToSelector:@selector(finishedLaodData)])
        [self.ctDelegate performSelector:@selector(finishedLaodData)];
    
    //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self performSelector:@selector(resetButtomFrame)];
}

-(void)initWithData{
    if(_isStrNULL(self.wwwUrl))return;
//    NSString *channelUrl = [[Globle shareInstance] getURLByID:@"getComment"];
//    NSString *requestUrl = [NSString stringWithFormat:channelUrl,@"20",@"1",[self.wwwUrl URLEncodedString]];
//   
//    IfengData_Request *request = [[IfengData_Request alloc] init];
//    request.url = requestUrl;
//    request.dataType = IfengData_Json;
//    request.priority = IfengData_RequestIgnoreCache;
//    CTCommentTable __weak *me=self;
//    [request onResponse:^(IfengData_Response *response)
//     {
//         
//         if(response && [response responseCode ] == 0 &&
//            response.responseObject && [response.responseObject respondsToSelector:@selector(objectForKey:)])
//         {
//             me.hidden = NO;
//             isReceviedSuccessed = YES;
//             
//             if(me.ctDelegate && [me.ctDelegate respondsToSelector:@selector(finishedLaodData)])
//                 [me.ctDelegate performSelector:@selector(finishedLaodData)];
//             
//             NSDictionary *commentData = (NSDictionary *)response.responseObject;
//             me.commentsDic = commentData;
//             me.content = [commentData sgrGetDictionaryForKey:@"comments"];
//             if(me.content && ![me.content isKindOfClass:[NSNull class]])
//             {
//                 me.hottestComments = [me.content sgrGetArrayForKey:@"hottest"];
//                 [me reloadData];
//                 [me performSelector:@selector(resetButtomFrame)];
//             }
//             else
//                 [me handleFailed];
//         }
//         else
//         {
//             [me handleFailed];
//         }
//         
//     }];
//    [request send:self];
}

- (void)handleFailed
{
    [self.table reloadData];
    [self hidenBottom];
    
    self.hidden = NO;
    isReceviedSuccessed = NO;
    
    if(self.ctDelegate && [self.ctDelegate respondsToSelector:@selector(finishedLaodData)])
        [self.ctDelegate performSelector:@selector(finishedLaodData)];
    
    [self performSelector:@selector(resetButtomFrame)];
}

#pragma mark -
#pragma mark Show More Comments Methods

- (void)showHiddedComments:(NSIndexPath *)indexpath
{
    [showHiddenFloorIndexPaths addObject:indexpath];
    [self.table reloadData];
    [self resetButtomFrame];
}

- (BOOL)indexPath:(NSIndexPath *)sourceIndexPath isExistInArray:(NSArray *)array
{
    if(!array || [array count] <= 0)
        return NO;
    for (NSIndexPath *indexPath in array) {
        if(sourceIndexPath.section == indexPath.section
           && sourceIndexPath.row == indexPath.row){
            return YES;
        }
    }
    return NO;
}

- (void)addReplayAtTableView:(UITableView *)tableView  atIndexPath:(NSIndexPath *)indexPath{
    
}

- (void)nameTapWithData:(NSDictionary *)dic withIndexPath:(NSIndexPath *)indexPath
{
    if(self.ctDelegate && [self.ctDelegate respondsToSelector:@selector(nameTapWithData:withIndexPath:)])
        [(CTCommentViewController *)self.ctDelegate nameTapWithData:dic withIndexPath:indexPath];
}

@end
